import { topicApi } from '/api/topic'
import { uploadFile } from '/api/file'
import { GlobalData } from '/store/state'
import { $event } from '/utils'
import { getServer } from '/store/mutations'
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
import getMessage from 'ts-msg-handler'

Page({
  data: {
    isFullScreen: GlobalData.isFullScreen,
    use: GlobalData.logged,
    config: {} as any,
    form: {
      name: '' as string,
      desc: '' as string,
      logo: '' as string,
      bg: '' as string,
      join_permission: 'afterAudit' as string,
      publish_permission: '' as string,
      topic_category_id: 0 as number,
      visible: 'visible' as string,
      expense: 0 as number,
      invited_audit: false as boolean,
      join_mode: 'open' as string,
    } as CreateTopicPayload,
    cropper: '' as any,
    logoCropper: '' as any,
    creating: false,
    bgParams: {
      width: 250,
      height: 125,
      max_width: 750,
      max_height: 375,
      export_scale: 1,
      disable_rotate: true,
      disable_ratio: true,
      limit_move: true,
      src: '' as string,
      show: false,
      scale: 1,
      imgSrc: '' as any,
    },
    logoParams: {
      width: 360,
      height: 360,
      max_width: 1080,
      max_height: 1080,
      mix_width: 1080,
      min_height: 1080,
      export_scale: 1,
      disable_rotate: true,
      disable_ratio: true,
      limit_move: true,
      src: '' as string,
      show: false,
      scale: 1,
      imgSrc: '' as any,
    },
    publishPermissions: [] as any,
    joinPermissions: [] as any,
    selected: 0 as any,
    joinSelected: '' as any,
    type: [],
    visible: false,
    join_mode: false,
    charge: false,
    price: '',
    isEditor: false,
    id: 0,
    user: {} as DomoUser,
    jurisdiction: { visible: false, hidden: false },
  },
  async onLoad(query) {
    wx.setNavigationBarTitle({
      title: `${query.editor ? '编辑' : '创建'}圈子`,
    })
    this.getTopicsType()
    this.getUserInfo()
    await topicApi.getTopicConfig().then((data: TopicConfig) => {
      const { publish_permissions, join_permissions } = data
      const publishPermissions = publish_permissions.filter(
        (pp: any) => pp.value !== 'byManager',
      ) as any
      // if (data.config.join_permission !== 'byManager') {
      //   this.setData({
      //     form: {
      //       ...this.data.form,
      //       join_permission: data.config.join_permission,
      //     },
      //   })
      // }
      this.setData({
        isFullScreen: GlobalData.isFullScreen,
        form: {
          ...this.data.form,
          publish_permission: publishPermissions[0].value,
        },
        config: data,
        publishPermissions,
        joinPermissions: join_permissions.filter((jp: any) => jp.value !== 'byManager'),
      })
    })
    if (query.editor) {
      //编辑
      const pages = getCurrentPages()
      const lastpage = pages[pages.length - 2]
      const lastpageData = lastpage.data.topic
      let selected = 0
      this.data.publishPermissions.map((i: { value: any }, index: number) => {
        if (i.value == lastpageData.publish_permission) {
          selected = index
        }
      })
      this.setData({
        [`bgParams.imgSrc.url`]: lastpageData.bg.url,
        [`logoParams.imgSrc.url`]: lastpageData.logo.url,
        [`form.name`]: lastpageData.name,
        [`form.desc`]: lastpageData.desc,
        [`form.topic_category_id`]: lastpageData.category.id,
        [`form.publish_permission`]: lastpageData.publish_permission,
        selected,
        [`form.visible`]: lastpageData.visible,
        visible: lastpageData.visible === 'hidden',
        charge: lastpageData.expense > 0,
        price: lastpageData.expense,
        join_mode: lastpageData.join_mode === 'need-audit',
        [`form.expense`]: lastpageData.expense,
        [`form.invited_audit`]: lastpageData.invited_audit,
        isEditor: true,
        id: lastpageData.id,
        publish_permission: lastpageData.publish_permission,
      })
    }
    const jurisdiction = await topicApi.canCreatTopic()
    this.setData({ jurisdiction })
  },
  onShow() {
    // if (!GlobalData.access.ugc) {
    //   wx.switchTab({
    //     url: '/pages/feed/list/list',
    //   })
    // }
    this.setData({
      // @ts-ignore
      cropper: this.selectComponent('#image-cropper'),
      // @ts-ignore
      logoCropper: this.selectComponent('#image-cropper-logo'),
    })
  },
  /** 获取用户信息 */
  getUserInfo() {
    const user = wx.getStorageSync(`${getServer()}/logged`).data
    this.setData({
      user,
    })
  },
  handleBgTap() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      success: ({ tempFilePaths: { [0]: path } }) => {
        this.setData({
          bgParams: {
            ...this.data.bgParams,
            src: path,
            show: true,
          },
        })
      },
    })
  },
  /** 取消选择图片 */
  cancel() {
    this.setData({
      bgParams: {
        ...this.data.bgParams,
        show: false,
      },
      logoParams: {
        ...this.data.logoParams,
        show: false,
      },
    })
  },
  handleLogoTap() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      success: ({ tempFilePaths: { [0]: path } }) => {
        this.setData({
          logoParams: {
            ...this.data.logoParams,
            src: path,
            show: true,
          },
        })
      },
    })
  },
  loadimage() {
    wx.hideLoading()
    this.data.cropper.imgReset()
  },
  loadlogoimage() {
    wx.hideLoading()
    this.data.logoCropper.imgReset()
  },
  clickcut(e: any) {
    //图片预览
    wx.previewImage({
      current: e.detail.url, // 当前显示图片的http链接
      urls: [e.detail.url], // 需要预览的图片http链接列表
    })
  },
  submitBg() {
    this.data.cropper.getImg((obj: any) => {
      this.setData({
        bgParams: {
          ...this.data.bgParams,
          imgSrc: obj,
          show: false,
        },
      })
    })
  },
  submitLogo() {
    this.data.logoCropper.getImg((obj: any) => {
      this.setData({
        logoParams: {
          ...this.data.logoParams,
          imgSrc: obj,
          show: false,
        },
      })
    })
  },
  // 设置圈子发言权限
  bindPickerChange({ detail: { value } }: { detail: any; value: string }) {
    const {
      data: { publishPermissions },
    } = this
    this.setData({
      form: {
        ...this.data.form,
        publish_permission: publishPermissions[value].value,
      },
      selected: parseInt(value),
    })
  },
  /**跳转到设置圈子发言的权限 */
  toPublishRules() {
    wx.navigateTo({
      url: '/mine/create-topic/publishRules/publishRules',
    })
  },
  bindJoinPickerChange({ detail: { value } }: { detail: any; value: string }) {
    const {
      data: { joinPermissions },
    } = this
    this.setData({
      form: {
        ...this.data.form,
        join_permission: joinPermissions[value].value,
      },
      joinSelected: parseInt(value),
    })
  },
  nameBindinput(e: any) {
    const {
      detail: { value },
    }: { detail: any; value: string } = e
    this.setData({
      form: {
        ...this.data.form,
        name: value,
      },
    })
  },
  descBindinput(e: any) {
    const {
      detail: { value },
    }: { detail: any; value: string } = e
    this.setData({
      form: {
        ...this.data.form,
        desc: value,
      },
    })
  },
  /** 获取圈子的分类 */
  async getTopicsType() {
    try {
      const type = await topicApi.getTopicClassify()
      this.setData({
        type: type.data,
        ['form.topic_category_id']: this.data.isEditor
          ? this.data.form.topic_category_id
          : type.data[0].id,
      })
    } catch (error) {
      wx.showToast({
        title: `${getMessage(error.data).getMessage()}`,
        icon: 'none',
      })
    }
  },
  /** 分类 */
  chooseType(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { id },
      },
    } = e
    this.setData({
      ['form.topic_category_id']: id,
    })
  },
  /** 私密圈子 */
  visibleChange(e: WechatMiniprogram.CustomEvent) {
    const {
      data: {
        jurisdiction: { hidden },
      },
    } = this
    const {
      detail: { value },
    } = e
    if (value && !hidden) {
      this.setData({
        visible: false,
      })
      wx.showToast({
        title: '创建的私密圈子数量已达到上限！',
        icon: 'none',
      })
      return
    }
    if (value) {
      // 私密圈子开关开启时，加入圈子需要圈主同意开关同步开启
      // 私密圈子开关关闭时，加入圈子需要圈主同意开关不同步
      this.setData({
        visible: value,
        ['form.visible']: value ? 'hidden' : 'visible',
        join_mode: value,
        ['form.join_mode']: value ? 'need-audit' : 'open',
        charge: false,
        ['form.expense']: value ? (this.data.price && this.data.charge ? +this.data.price : 0) : 0,
        price: value ? this.data.price + '' : '',
      })
    } else {
      this.setData({
        visible: value,
        ['form.visible']: value ? 'hidden' : 'visible',
        charge: false,
        ['form.expense']: value ? (this.data.price && this.data.charge ? +this.data.price : 0) : 0,
        price: value ? this.data.price + '' : '',
      })
    }
  },
  /** 是否需要圈主审核 */
  joinMode(e: WechatMiniprogram.CustomEvent) {
    const {
      detail: { value },
    } = e
    if (value && this.data.charge) {
      wx.showToast({
        title: '付费圈子不需要审核哟',
        icon: 'none',
        duration: 1000,
      })
      this.setData({
        join_mode: false,
        ['form.join_mode']: 'open',
      })
      return
    }
    if (!value && !this.data.charge && this.data.visible) {
      wx.showToast({
        title: '私密不付费的圈子必须审核哟',
        icon: 'none',
        duration: 1000,
      })
      this.setData({
        join_mode: true,
        ['form.join_mode']: 'need-audit',
      })
      return
    }
    this.setData({
      join_mode: value,
      ['form.join_mode']: value ? 'need-audit' : 'open',
    })
  },
  /** 是否付费 */
  chargeChange(e: WechatMiniprogram.CustomEvent) {
    const {
      detail: { value },
    } = e
    if (value && !this.data.visible) {
      wx.showToast({
        title: '私密圈子才能设置付费哦',
        icon: 'none',
        duration: 1000,
      })
      this.setData({
        charge: false,
      })
      return
    }
    this.setData({
      charge: value,
      ['form.expense']: value ? +this.data.price : 0,
      price: value ? this.data.price + '' : '',
      join_mode: !value,
      ['form.join_mode']: value ? 'open' : 'need-audit',
    })
  },
  /** 输入付费的价格 */
  inputPrice(e: WechatMiniprogram.CustomEvent) {
    const {
      detail: { value },
    } = e
    this.setData({
      price: value,
      ['form.expense']: +value,
    })
  },
  /** 创建圈子 */
  async doSubmit() {
    const {
      data: { form, bgParams, logoParams },
    } = this
    this.setData({ creating: true })
    const { imgSrc: bg } = bgParams
    const { imgSrc: logo } = logoParams
    try {
      bg.width ? (form.bg = await uploadFile(bg.url)) : delete form.bg
      logo.width ? (form.logo = await uploadFile(logo.url)) : delete form.logo
      if ((form.bg && form.logo) || this.data.isEditor) {
        ; (this.data.isEditor
          ? topicApi.updataTopic(this.data.id, form)
          : topicApi.createTopic(form)
        )
          .then(() => {
            this.setData({ creating: false })
            wx.showToast({
              title: this.data.isEditor ? '修改成功' : '创建成功',
              icon: 'success',
            })
            this.data.isEditor ? $event.emit('after:topicEditor') : ''
            setTimeout(() => {
              wx.navigateBack({
                delta: 1,
              })
            }, 1500)
          })
          .catch((res) => {
            wx.showToast({
              title: `${getMessage(res.data).getMessage()}`,
              icon: 'none',
            })
            this.setData({ creating: false })
          })
      } else {
        wx.showToast({
          title: `请重新上传圈子图片`,
          icon: 'none',
        })
        this.setData({ creating: false })
      }
    } catch (res) {
      wx.showToast({
        title: `${getMessage(res.data).getMessage()}`,
        icon: 'none',
      })
      this.setData({ creating: false })
    }
  },
})
